<template>
  <view class="factory-recruitment">
    <view class="post-form">
      <view class="form-group">
        <text class="label">职位名称 <text class="required">*</text></text>
        <input
          type="text"
          v-model="formData.positionName"
          class="input"
          :class="{ 'error-border': formErrors.positionName }"
          placeholder="例如：SMT技术员"
        />
        <text v-if="formErrors.positionName" class="error-text">{{
          formErrors.positionName
        }}</text>
      </view>

      <!-- 职位类型输入框 -->
      <view class="form-group">
        <text class="label">职位类型</text>
        <view
          class="picker-input"
          :class="{ 'error-border': formErrors.type }"
          @click="showTypePicker = true"
        >
          <text class="picker-text">{{
            pickerTitle || "请选择职位类型"
          }}</text>
        </view>
        <text v-if="formErrors.type" class="error-text">{{
          formErrors.type
        }}</text>
      </view>

      <view class="form-group">
        <text class="label">公司名称 <text class="required">*</text></text>
        <input
          type="text"
          v-model="formData.corporateName"
          class="input"
          :class="{ 'error-border': formErrors.corporateName }"
          placeholder="例如：中芯科技制造厂"
        />
        <text v-if="formErrors.corporateName" class="error-text">{{
          formErrors.corporateName
        }}</text>
      </view>

      <view class="form-group">
        <text class="label">工作地点 <text class="required">*</text></text>
        <input
          type="text"
          v-model="formData.location"
          class="input"
          :class="{ 'error-border': formErrors.location }"
          placeholder="例如：松江区"
        />
        <text v-if="formErrors.location" class="error-text">{{
          formErrors.location
        }}</text>
      </view>

      <view class="form-group">
        <text class="label">经验要求 <text class="required">*</text></text>
        <input
          type="text"
          v-model="formData.experience"
          class="input"
          :class="{ 'error-border': formErrors.experience }"
          placeholder="例如：2年以上经验"
        />
        <text v-if="formErrors.experience" class="error-text">{{
          formErrors.experience
        }}</text>
      </view>

      <view class="form-group">
        <text class="label">薪资范围 <text class="required">*</text></text>
        <view class="salary-input flex items-center">
          <input
            type="number"
            v-model="formData.salaryMin"
            class="input flex-1"
            :class="{
              'error-border': formErrors.salaryMin || formErrors.salaryRange,
            }"
            placeholder="最低薪资"
          />
          <text class="mx-[24rpx]">至</text>
          <input
            type="number"
            v-model="formData.salaryMax"
            class="input flex-1"
            :class="{
              'error-border': formErrors.salaryMax || formErrors.salaryRange,
            }"
            placeholder="最高薪资"
          />
          <text class="ml-[24rpx]">/月</text>
        </view>
        <text v-if="formErrors.salaryMin" class="error-text">{{
          formErrors.salaryMin
        }}</text>
        <text v-if="formErrors.salaryMax" class="error-text">{{
          formErrors.salaryMax
        }}</text>
        <text v-if="formErrors.salaryRange" class="error-text">{{
          formErrors.salaryRange
        }}</text>
      </view>

      <view class="form-group">
        <text class="label">职位标签</text>
        <view class="tags-container flex flex-wrap gap-[20rpx]">
          <view
            v-for="(tag, index) in tags"
            :key="index"
            :class="['tag-option', { selected: tag.selected }]"
            @click="toggleTag(index)"
          >
            {{ tag.name }}
          </view>
        </view>
      </view>

      <view class="form-group">
        <text class="label">职位描述 <text class="required">*</text></text>
        <nut-textarea
          v-model="formData.description"
          class="textarea"
          :class="{ 'error-border': formErrors.description }"
          placeholder="请输入职位描述..."
        />
        <text v-if="formErrors.description" class="error-text">{{
          formErrors.description
        }}</text>
      </view>

      <nut-button class="submit-btn" @click="submitForm">发布招聘</nut-button>
    </view>
    <view class="preview">
      <text class="preview-title text-[28rpx] font-bold">预览效果</text>
      <view class="job-card">
        <text class="job-title text-[28rpx] font-bold">{{
          formData.positionName || "SMT技术员"
        }}</text>
        <text class="company-info text-[24rpx] text-[#666]">
          {{ formData.corporateName || "中芯科技制造厂" }} ·
          {{ formData.location || "松江区" }} ·
          {{ formData.experience || "2年以上经验" }}
        </text>
        <text class="salary text-[32rpx] text-[#f44336] font-bold">
          ¥{{ formData.salaryMin || 6500 }}-{{ formData.salaryMax || 8500 }}/月
        </text>
        <view class="tags flex flex-wrap gap-[16rpx]">
          <text
            v-for="(tag, index) in selectedTags"
            :key="index"
            class="tag bg-[#f5f5f5] text-[#666] px-[16rpx] py-[8rpx] rounded-[8rpx] text-[24rpx]"
          >
            {{ tag }}
          </text>
        </view>
        <view
          class="footer flex justify-between text-[24rpx] text-[#999] mt-[20rpx]"
        >
          <text>2天前发布</text>
          <nut-button
            class="apply-btn bg-[#1976d2] text-white px-[30rpx] py-[10rpx] rounded-[8rpx] text-[28rpx]"
            >立即申请</nut-button
          >
        </view>
      </view>
    </view>
    <!-- 职位类型选择器弹窗 -->
    <nut-popup v-model:visible="showTypePicker" position="bottom" round>
      <nut-picker
        :columns="jobTypes.map((item) => ({ text: item.type, value: item.id }))"
        :title="pickerTitle"
        @confirm="onTypeConfirm"
        @cancel="showTypePicker = false"
      />
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive,computed } from "vue";
import { showToast } from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { post } from "@/utils/request";
import Taro from "@tarojs/taro";

export interface JobPost {
  corporateName?: string;
  deadline?: string;
  description?: string;
  experience?: string;
  location?: string;
  positionName?: string;
  salaryMax?: string;
  salaryMin?: string;
  type?: number;
  [property: string]: any;
}

// 表单数据
const formData = reactive<JobPost>({});

/** 表单数据类型 - 仅保留职位类型相关字段 */
interface JobFormData {
  id: number;
  type: string;
}

/** 职位类型选项 */
// const jobTypes = ["普工", "技工", "管理", "质检", "仓储", "后勤", "其他"];
const jobTypes = ref<JobFormData[]>([])

/** 职位类型选择器显示状态 */
const showTypePicker = ref(false);
const pickerTitle = ref()

/** 职位类型选择器确认事件 */
function onTypeConfirm(value: any) {
  // 将选择的职位类型赋值给表单
  formData.type = value?.selectedValue[0] || "";
  console.log(formData.type)
    // 更新标题（可选）
  const selectedType = jobTypes.value.find(item => item.id === formData.type);
  pickerTitle.value = selectedType?.type || '选择职位类型';
  // 关闭弹窗
  showTypePicker.value = false;
}

// 计算属性：根据 id 获取 type 名称
// const typeName = computed(() => {
//   const selectedType = jobTypes.value.find(item => item.id == formData.type);
//   console.log(selectedType?.type)
//   return selectedType?.type || '请选择职位类型';
// })

// 职位标签--测试
const tags = ref([
  { name: "两班倒", selected: false },
  { name: "包吃住", selected: false },
  { name: "年终奖金", selected: false },
  { name: "带薪年假", selected: false },
  { name: "五险一金", selected: false },
  { name: "周末双休", selected: false },
]);

// 选中的标签
const selectedTags = ref<string[]>([]);

// 表单验证错误信息
const formErrors = reactive<
  Partial<Record<keyof JobPost | "salaryRange", string>>
>({});

// 切换标签选择状态
const toggleTag = (index: number) => {
  tags.value[index].selected = !tags.value[index].selected;
  // 更新选中的标签列表
  selectedTags.value = tags.value
    .filter((tag) => tag.selected)
    .map((tag) => tag.name);
};

// 表单验证方法
const validateForm = (): boolean => {
  const errors: Partial<Record<keyof JobPost | "salaryRange", string>> = {};

  // 职位名称验证
  if (!formData.positionName?.trim()) {
    errors.positionName = "请输入职位名称";
  }

  // 公司名称验证
  if (!formData.corporateName?.trim()) {
    errors.corporateName = "请输入公司名称";
  }

  if (!formData.type) {
    errors.type = "请选择职位类型";
  }

  // 工作地点验证
  if (!formData.location?.trim()) {
    errors.location = "请输入工作地点";
  }

  // 经验要求验证
  if (!formData.experience?.trim()) {
    errors.experience = "请输入经验要求";
  }

  // 最低薪资验证
  if (!formData.salaryMin?.trim()) {
    errors.salaryMin = "请输入最低薪资";
  } else if (isNaN(Number(formData.salaryMin))) {
    errors.salaryMin = "最低薪资必须为数字";
  }

  // 最高薪资验证
  if (!formData.salaryMax?.trim()) {
    errors.salaryMax = "请输入最高薪资";
  } else if (isNaN(Number(formData.salaryMax))) {
    errors.salaryMax = "最高薪资必须为数字";
  }

  // 薪资范围验证（当两者都填写时）
  if (
    formData.salaryMin &&
    formData.salaryMax &&
    !errors.salaryMin &&
    !errors.salaryMax
  ) {
    const min = Number(formData.salaryMin);
    const max = Number(formData.salaryMax);
    if (min >= max) {
      errors.salaryRange = "最低薪资必须小于最高薪资";
    }
  }

  // 职位描述验证
  if (!formData.description?.trim()) {
    errors.description = "请输入职位描述";
  }

  // 更新错误信息
  Object.assign(formErrors, errors);

  // 返回验证结果（无错误则为有效）
  return Object.keys(errors).length === 0;
};

// 提交表单
const submitForm = async () => {
  // 先进行表单验证
  if (!validateForm()) {
    showToast({ title: "请完善必填信息", icon: "none", duration: 2000 });
    return;
  }

  // 显示加载状态
  Taro.showLoading({ title: "发布中..." });

  try {
    // 构建提交数据（包含选中的标签）
    const submitData = {
      ...formData,
      tags: selectedTags.value,
    };

    // 提交数据到接口
    const res = await post("/recruitment/save", submitData);
    console.log("====>", res);
    if (res.code == 0) {
      showToast({ title: "发布成功", icon: "success", duration: 2000 });
      // 重置表单
      Object.keys(formData).forEach((key) => {
        formData[key as keyof JobPost] = "";
      });
      tags.value.forEach((tag) => (tag.selected = false));
      selectedTags.value = [];
    } else {
      showToast({ title: res.msg || "发布失败", icon: "none", duration: 2000 });
    }
  } catch (error) {
    showToast({ title: "网络错误，请稍后重试", icon: "none", duration: 2000 });
  } finally {
    // 隐藏加载状态
    Taro.hideLoading();
  }
};

// 招聘类型
const jobRecruitmentType = async () => {
  const res = await post("/dictionary/recruitmentType");
  if (res.code == "0") {
    jobTypes.value = res.data.map((item: any) => ({
      id: item.columns.id,
      type: item.columns.name,
    }));
  }
};
jobRecruitmentType()
</script>

<style>
.post-form {
  background-color: white;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 30rpx;
}

.label {
  display: block;
  margin-bottom: 8rpx;
  font-weight: bold;
  color: #555;
  font-size: 28rpx;
}

.required {
  color: #ff4d4f;
}

.input,
.textarea {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

/* 错误状态样式 */
.error-border {
  border-color: #ff4d4f !important;
}

.error-text {
  color: #ff4d4f;
  font-size: 24rpx;
  margin-top: 8rpx;
  display: block;
  line-height: 1.4;
}

.salary-input {
  display: flex;
  align-items: center;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.tag-option {
  background-color: #f0f0f0;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  cursor: pointer;
  font-size: 24rpx;
  transition: all 0.2s;
}

.tag-option.selected {
  background-color: #e3f2fd;
  color: #1976d2;
  border-color: #1976d2;
  border: 1rpx solid;
}

.submit-btn {
  background-color: #1976d2 !important;
  color: white !important;
  width: 100%;
  margin-top: 40rpx;
  padding: 24rpx 40rpx;
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
}

.preview {
  margin-top: 40rpx;
  background-color: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.container {
  width: 750rpx;
  max-width: 100%;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  margin-bottom: 40rpx;
  height: 60rpx;
}

.header h1 {
  color: #333;
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.salary-input span {
  margin: 0 24rpx;
}

.preview-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid #eee;
}

.job-card {
  border: 1rpx solid #eee;
  border-radius: 12rpx;
  padding: 30rpx;
  position: relative;
}

.job-card::before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 4rpx;
  background-color: #1976d2;
  border-radius: 12rpx 0 0 12rpx;
}

.job-title {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.company-info {
  color: #666;
  font-size: 24rpx;
  margin-bottom: 10rpx;
}

.salary {
  color: #f44336;
  font-size: 32rpx;
  font-weight: bold;
  margin: 20rpx 0;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin: 20rpx 0;
}

.tag {
  background-color: #f5f5f5;
  color: #666;
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.footer {
  display: flex;
  justify-content: space-between;
  color: #999;
  font-size: 24rpx;
  margin-top: 20rpx;
}

.apply-btn {
  background-color: #1976d2;
  color: white;
  border: none;
  padding: 10rpx 30rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  cursor: pointer;
}

/* 输入框聚焦样式 */
input:focus,
textarea:focus {
  outline: none;
  border-color: #1976d;
}

/* 表单组样式 - 包含职位类型输入框整体布局 */
.form-group {
  margin-bottom: 30rpx;
}

/* 标签样式 - 职位类型文字标签 */
.label {
  display: block;
  margin-bottom: 8rpx;
  font-weight: bold;
  color: #555;
  font-size: 28rpx;
}

/* 选择器输入框样式 - 职位类型点击区域 */
.picker-input {
  display: flex;
  align-items: center;
  min-height: 76rpx;
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: white;
  cursor: pointer;
}

/* 选择器文字样式 - 职位类型显示文字 */
.picker-text {
  color: #333;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 错误提示样式 - 职位类型未选择时的错误文字 */
.error-text {
  color: #f44336;
  font-size: 24rpx;
  margin-top: 8rpx;
  display: block;
}

/* 错误边框样式 - 职位类型未选择时的红色边框 */
.error-border {
  border-color: #f44336 !important;
}

/* 输入框聚焦样式 - 职位类型选择框聚焦效果 */
.picker-input:focus {
  outline: none;
  border-color: #1976d2;
}
/* 去除 nut-textarea 的内边距 */
.nut-textarea {
  padding: 0 !important;  /* 使用 !important 强制覆盖组件默认样式 */
}
</style>
